﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace EdexApiClient
{
    public partial class EdexApiContext
    {
        /// <summary>
        /// Получить входящие накладные
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Invoices> GetIncomingInvoices()
        {
            return this.GetIncomingInvoices(String.Empty);
        }

        /// <summary>
        /// Получить входящие накладные
        /// </summary>
        /// <returns></returns>
        public System.IO.Stream GetIncomingInvoicesCommerceML(Guid[] id)
        {
            var uri = String.Format("IncomingInvoices/?api_key={0}&$filter={1}", 
                this.session.APIKEY, 
                String.Join(" or ", id.Select(r => String.Format("GUID_RECORD eq guid'{0}'", r))));

            return this.Download(uri, "application/commerceML");
        }

        /// <summary>
        /// Получить входящие накладные
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public IEnumerable<Invoices> GetIncomingInvoices(string search)
        {
            var uri = String.Format("IncomingInvoices/?api_key={0}", this.session.APIKEY);

            if (!String.IsNullOrEmpty(search))
                uri += "&$filter=substringof('" + search + "', DOC_NUMBER) eq true&$top=100";

            uri += "&$orderby=DOC_DATE";

            return this.GetData<List<Invoices>>(uri);
        }

        /// <summary>
        /// Получить детализацию по входящей накладной
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Invoices GetIncomingInvoice(string id)
        {
            return this.GetData<Invoices>(String.Format("IncomingInvoices/{0}/?api_key={1}", id, this.session.APIKEY));
        }

        /// <summary>
        /// Получить детализацию по позиции во входящей накладной
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public InvoiceLines GetIncomingInvoiceLine(string id)
        {
            return this.GetData<InvoiceLines>(String.Format("IncomingInvoiceLines/{0}/?api_key={1}", id, this.session.APIKEY));
        }
    }
}